<template>
  <div>
    <el-input v-model="search" placeholder="输入关键字搜索" />
    <el-button type="primary" @click="openAdd">添加商店</el-button>
    <el-dialog
      title="添加商品"
      :visible.sync="centerDialogVisible"
      width="30%"
      center
    >
      <el-form label-width="80px">
        <el-form-item label="商品名称">
          <el-input v-model="newArr.name"></el-input>
        </el-form-item>

        <el-form-item label="商品类型" prop="type">
          <el-checkbox-group v-model="newArr.classify">
            <el-checkbox
              v-for="(item, index) in typeStu"
              :label="item"
              :key="index"
              >{{ item }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="价格">
          <el-input v-model.number="newArr.price"></el-input>
        </el-form-item>
        <el-form-item label="生产日期" required>
          <el-form-item prop="date1">
            <el-date-picker
              type="date"
              placeholder="选择日期"
              v-model="newArr.production"
              style="width: 100%"
              value-format="timestamp"
              format="yyyy 年 MM 月 dd 日"
              :picker-options="pickerOptions"
            ></el-date-picker>
          </el-form-item>
        </el-form-item>
        <el-form-item label="产地">
          <el-input v-model="newArr.publishing"></el-input>
        </el-form-item>

        <el-form-item label="详情页图">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:3002/uploadFile"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            multiple
          >
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-carousel :interval="4000" type="card" height="200px">
            <el-carousel-item
              v-for="(item, index) in newArr.images"
              :key="index"
            >
              <img
                :src="`http://localhost:3002/images/${item}`"
                alt=""
                @click="dleImg(index)"
              />
            </el-carousel-item>
          </el-carousel>
        </el-form-item>

        <el-form-item label="封面">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:3002/uploadFile"
            :on-success="handleAvatarSucces"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="newArr.poster"
              :src="`http://localhost:3002/images/${newArr.poster}`"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="简介">
          <el-input
            type="textarea"
            :rows="2"
            v-model="newArr.desc"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="sureAdd">确认添加</el-button>
        <el-button type="primary" @click="centerDialogVisible = false"
          >取 消</el-button
        >
      </span>
    </el-dialog>

    <el-table
      :data="
        goodsStu.rows.filter(
          (data) =>
            !search ||
            data.name.toLowerCase().includes(search.toLowerCase()) ||
            data.price.toLowerCase().includes(search.toLowerCase())
        )
      "
      border
      style="width: 100%"
    >
      <el-table-column label="商品名称" prop="name"> </el-table-column>
      <el-table-column label="商品分类" prop="classify">
        <template slot-scope="scope">
          <el-tag
            v-for="(item, index) in scope.row.classify"
            :key="index"
            type="success"
            >{{ item }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="价格" prop="price"> </el-table-column>
      <el-table-column label="生产日期" prop="production">
        <template slot-scope="scope">
          {{ getFormatTime(scope.row.production) }}
        </template>
      </el-table-column>
      <el-table-column label="产地" prop="publishing"> </el-table-column>
      <el-table-column label="详情页轮播图" prop="images">
        <template slot-scope="scope">
          <el-carousel :interval="2000" height="75px" loop>
            <el-carousel-item
              v-for="(item, index) in scope.row.images"
              :key="index"
              class="box"
            >
              <img :src="`http://localhost:3002/images/${item}`" class="img" />
            </el-carousel-item>
          </el-carousel>
        </template>
      </el-table-column>

      <el-table-column label="封面" prop="poster">
        <template slot-scope="scope">
          <img
            :src="`http://localhost:3002/images/${scope.row.poster}`"
            alt=""
            class="img"
          />
        </template>
      </el-table-column>
      <el-table-column label="简介" prop="desc"> </el-table-column>
      <el-table-column align="right" label="操作" width="180">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <template>
      <div class="block">
        <el-pagination
          @size-change="sizeChange"
          @current-change="currentChange"
          :page-sizes="[4, 10, 15]"
          :page-size="4"
          layout="total, sizes, prev, pager, next, jumper"
          :total="goodsStu.total"
        >
        </el-pagination>
      </div>
    </template>
  </div>
</template>

<script>
export default {
  data() {
    return {
      centerDialogVisible: false,
      search: "",
      typeStu: ["苹果", "草莓", "梨", "西瓜", "葡萄", "香蕉"],
      newArr: {
        name: "", // 商品名称
        classify: [], // 商品分类 ['苹果','香蕉','西瓜'....]
        price: "", // 价格
        production: "", // 生产日期
        publishing: "", // 产地
        images: [],
        poster: "", // 封面
        desc: "", // 简介
        adminId: "", // 门店所属管理员id
        shopsId: [], // 所属门店id
        isAvail: 1, // 商品上架前是否通过审核（0：未通过；1：申请中；2：已通过）
      },
      arr: {},
      falter: false,
      _id: "",
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
    };
  },
  methods: {
    openAdd() {
      this.centerDialogVisible = true;
      this.newArr.name = ""; // 商品名称
      this.newArr.classify = []; // 商品分类 ['苹果','香蕉','西瓜'....]
      this.newArr.price = ""; // 价格
      this.newArr.production = ""; // 生产日期
      this.newArr.publishing = ""; // 产地
      this.newArr.images = [];
      this.newArr.poster = ""; // 封面
      this.newArr.desc = ""; // 简介
      this.newArr.shopsId = []; // 所属门店id
      this.newArr.isAvail = 1; // 商品上架前是否通过审核（0：未通过；1：申请中；2：已通过）
    },
    dleImg(index) {
      this.newArr.images.splice(index, 1);
    },
    sureAdd() {
      if (this.falter) {
        this.newArr._id = this._id;
        this.$store.commit("goods/udtStu", this.newArr);
        console.log(this.newArr);
        this.falter = false;
        this.centerDialogVisible = false;
      } else {
        this.$store.commit("goods/addStu", this.newArr);
        this.centerDialogVisible = false;
      }
      console.log(this.falter);
    },
    sizeChange(val) {
      this.$store.dispatch("goods/get", { id: "", current: "", size: val });
    },
    currentChange(val) {
      this.$store.dispatch("goods/get", { id: "", size: "", current: val });
    },
    handleAvatarSucces(res, file) {
      this.newArr.poster = res.saveName;
    },
    handleAvatarSuccess(res, file) {
      this.newArr.images.push(res.saveName);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    handleEdit(index, row) {
      this.newArr.name = row.name;
      this.newArr.classify = row.classify;
      this.newArr.price = row.price;
      this.newArr.production = row.production;
      this.newArr.publishing = row.publishing;
      this.newArr.images = row.images;
      this.newArr.poster = row.poster;
      this.newArr.desc = row.desc;
      this.newArr.adminId = row.adminId;
      this.newArr.shopsId = row.shopsId;
      this.newArr.isAvail = row.isAvail;
      this._id = row._id;
      this.falter = true;
      this.centerDialogVisible = true;
    },

    handleDelete(index, row) {
      this.$store.commit("goods/dltStu", row._id);
      let id = "";
      let admid = localStorage.getItem("Jurisdiction");
      if (admid == 2) {
        id = localStorage.getItem("ID");
        this.newArr.adminId = id;
      }
      this.$store.dispatch("goods/get", { id: id, size: "", current: "" });
    },
  },
  computed: {
    goodsStu() {
      return this.$store.getters.goodsStu;
    },
    getFormatTime: function () {
      return (timestamp) => {
        function formatDate(now) {
          var year = now.getFullYear(); //取得4位数的年份
          var month = now.getMonth() + 1; //取得日期中的月份，其中0表示1月，11表示12月
          var date = now.getDate(); //返回日期月份中的天数（1到31）
          return year + "-" + month + "-" + date;
        }
        parseInt(timestamp);
        var d = new Date(parseInt(timestamp));
        return formatDate(d);
      };
    },
  },
  created() {
    let id = "";
    let admid = localStorage.getItem("Jurisdiction");
    if (admid == 2) {
      id = localStorage.getItem("ID");
      this.newArr.adminId = id;
    }
    this.$store.dispatch("goods/get", { id: id, size: "", current: "" });
  },
};
</script>

<style>
.infinite-list {
  display: flex;
}
.infinite-list-item {
  border: 1px solid;
  list-style: none;
  width: 180px;
  height: 180px;
}
img {
  width: 178px;
  height: 178px;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar-uploader {
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  margin: 10px;
}
li {
  list-style: none;
}
.box {
  height: 75px;
}
.img {
  width: 125px;
  height: 75px;
}
</style>